package com.tpshion.deploy.controller;

import com.alibaba.fastjson.JSON;
import com.tpshion.deploy.common.constant.MsgType;
import com.tpshion.deploy.common.support.MsgContext;
import com.tpshion.deploy.common.support.MsgData;
import com.tpshion.deploy.common.support.Result;
import com.tpshion.deploy.handler.SendMsgHandler;
import com.tpshion.deploy.task.support.TaskContext;
import com.tpshion.deploy.task.support.TaskData;
import com.tpshion.deploy.task.support.TaskManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private SendMsgHandler sendMsgHandler;

    @Resource
    private TaskManager taskManager;

    @GetMapping("/msg")
    public Result msg(String taskId, String msg){
        log.info("msg taskId:{} msg:{}", taskId, msg);
        MsgData msgData = new MsgData();
        msgData.setType(MsgType.TEXT.getType());
        msgData.setData(msg);

        MsgContext msgContext = new MsgContext();
        msgContext.setTaskId(taskId);
        msgContext.setMsgData(msgData);
        sendMsgHandler.sendMsg(msgContext);
        return Result.ok();
    }

    @GetMapping("/task")
    public Result task(){
        String json = "[\n" +
                "  {\n" +
                "    \"taskId\": \"1\",\n" +
                "    \"taskType\": \"CODE\",\n" +
                "    \"sort\": 1,\n" +
                "    \"status\": 0\n" +
                "  },\n" +
                "  {\n" +
                "    \"taskId\": \"1\",\n" +
                "    \"taskType\": \"BUILD\",\n" +
                "    \"sort\": 2,\n" +
                "    \"status\": 0\n" +
                "  },\n" +
                "  {\n" +
                "    \"taskId\": \"1\",\n" +
                "    \"taskType\": \"PACKAGE\",\n" +
                "    \"sort\": 3,\n" +
                "    \"status\": 0\n" +
                "  },\n" +
                "  {\n" +
                "    \"taskId\": \"1\",\n" +
                "    \"taskType\": \"DEPLOY\",\n" +
                "    \"sort\": 4,\n" +
                "    \"status\": 0\n" +
                "  }\n" +
                "]";
        List<TaskData> taskList = JSON.parseArray(json, TaskData.class);
        TaskContext taskContext = new TaskContext();
        taskContext.setTaskId("1");
        taskContext.setList(taskList);
        taskManager.startTask(taskContext);
        return Result.ok();
    }

    @GetMapping("/stop")
    public Result stop(String taskId){
        taskManager.removeTask(taskId);
        return Result.ok();
    }

}
